package com.github.yangyishe;

public class ListNode {
    public int val;
    public ListNode next;
    public ListNode() {}
    public ListNode(int val) { this.val = val; }
    public ListNode(int val, ListNode next) { this.val = val; this.next = next; }

//    @Override
//    public String toString(){
//        if (next!=null) {
//            return val+","+next;
//        }else{
//            return val+"";
//        }
//    }


    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                '}';
    }

    public static ListNode getInstance(int[] arr){
        return getInstance(arr,-1);
    }

    /**
     * 快速构建链表
     * @param arr
     * @param pos
     * @return
     */
    public static ListNode getInstance(int[] arr, int pos){
        ListNode temp=null;
        ListNode result=null;
        ListNode posNode=null;
        for(int i=0;i<arr.length;i++){
            int num=arr[i];
            ListNode node=new ListNode(num);
            if(i==pos){
                posNode=node;
            }
            if(temp==null){
                temp=node;
                result=node;
            }else{
                // 此处递归创建node
                temp.next=node;
                temp=node;
            }

        }
        if(posNode!=null){
            temp.next=posNode;
        }


        return result;
    }

    public void print(){
        System.out.println(this);
        if(this.next!=null){
            this.next.print();
        }
    }
}
